package com.gongpingjialoan.activity.car;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.category.CategoryActivity;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.main.CitySelectAvtivity;
import com.gongpingjialoan.activity.main.MainActivity;
import com.gongpingjialoan.adapter.NewHotBrandAdapter;
import com.gongpingjialoan.adapter.car.CarlistSelectFilterAdapter;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.bean.Domain;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.bean.SelectBean;
import com.gongpingjialoan.bean.car.ModelDetialBean;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.CarListFilterData;
import com.gongpingjialoan.data.CategoryData;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.widget.LoadingDialog;
import com.gongpingjialoan.widget.MyGridView;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

/**
 * 筛选
 * Created by Administrator on 2015/12/14.
 */
public class CarListFilterActivity extends BaseActivity implements View.OnClickListener, NetDataJson.OnNetDataJsonListener, AdapterView.OnItemClickListener {
    private NetDataJson netWork;

    private NetDataJson modelDetailnetWork;

    private CarListFilterData data = CarListFilterData.getInstance();

    //品牌    (单选)
    private String[] brands = {"品牌选择", "品牌不限"};
    //    //城市    (单选)
//    private String[] citys = {"手动选择", "不限"};
    //价格    (单选)
    private String[] show_prices = {"3万以下", "3-5万", "5-10万", "10-15万", "价格不限"};
    private String[] need_prices = {"0-3", "3-5", "5-10", "10-15", ""};
    //车龄    (多选)
    private String[] show_carAge = {"1年以内", "1-3年", "3-5年", "5年以上", "车龄不限"};
    private String[] need_carAge = {"2016-2017", "2014-2016", "2012-2014", "-2012", ""};
    //颜色   (多选)
    private String[] show_color = {"黑", "白", "灰", "红", "银", "蓝", "金", "棕", "颜色不限"};
    private String[] need_color = {"黑", "白", "灰", "红", "银", "蓝", "金", "棕", ""};

    //用途    (多选)
    private String[] show_carModel = {"微型车", "小型车", "紧凑型车", "中级车", "中高级车", "SUV", "跑车", "豪华车", "商务车", "车型不限"};
    private String[] need_carModel = {"mini_car", "small_car", "compact_car", "middle_car", "middle_super_car", "suv", "super_car", "luxury_car", "mpv", ""};


    //车源类型  (多选)
    private String[] show_carSource = {"商家", "个人", "类型不限"};
    private String[] need_carSource = {"dealer", "private", ""};
    //车辆属性  (多选)
    private String[] show_carProperty = {"进口", "合资", "国产", "产地不限"};
    private String[] need_carProperty = {"import", "joint_venture", "domestic", ""};
    //排量    (多选)
    private String[] show_displacement = {"1.0升以内", "1.1-1.6升", "1.7-2.0升", "2.1-2.5升", "2.5升以上", "排量不限"};
    private String[] need_displacement = {"0-1.0", "1.1-1.6", "1.7-2.0", "2.1-2.5", "2.6-10.0", ""};
    //变速箱 (多选)
    private String[] show_speedChange = {"手动", "自动", "变速箱不限"};
    private String[] need_speedChange = {"manual", "automatic", ""};

    private LoadingDialog loadingDialog;
    //城市,重置
    private TextView resetT, registerTextView;
    //回退
    private LinearLayout closeLl;
    //确认
    private TextView completeBtn, domainTextView, buxianTextView;

    private ArrayList<Domain> mDomains;

    private MyGridView hotBrandGridView;

    private List<Map<String, String>> hotBrandList = new ArrayList<Map<String, String>>();

    private MyGridView gv_color, gV_brand, gV_price, gV_carAge, gV_carModel, gV_carSource, gV_carProperty, gV_displacement, gV_speedChange;
    private CarlistSelectFilterAdapter adapter_color, adapter_brand, adapter_price, adapter_carAge, adapter_carModel, adapter_carSource, adapter_carProperty, adapter_displacement, adapter_speedChange;

    List<SelectBean> list_brands, list_carcolor, list_prices, list_carAge, list_carModel, list_carSource, list_carProperty, list_displacement, list_speedChange;

    Bundle bundle;
    //品牌
    private final int REQUEST_BRAND = 2;
    public String mBrandSlug, mBrandName, mModelSlug, mModelName, mModelDetailName, mModelDetailSlug, mModelThumbnail, maxprice;
    private String isCut, is_certify;
    //城市
    private TextView cityT;
    private final int REQUEST_CITY_FRAGMENT = 1;
    private final int REQUEST_DOMAIN = 3;
    private View mainView;
    //开始价格,截止价格
    private EditText start_priceT, end_priceT;
    private String showcolor_name, showage_name, show_domain, showmoder_name, showcarProperty_name, show_carsourcename, show_speedchangename, show_displacementname, show_pricename;
    String str_city, str_province, str_mile, str_color, str_domain, str_prices, str_carAge, str_carModel, str_carSource, str_carProperty, str_displacement, str_speedChange;

    private NewHotBrandAdapter hotBrandAdapter;
    public CategoryData mCategoryData;
    private NetDataJson registerNetDataJson;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isSendData = true;
        action = "buy_market_filter";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_filter);
        loadingDialog = new LoadingDialog(this);

        netWork = new NetDataJson(this);
        netWork.setUrl(API.carListFilter);
        initView();

    }

    public void initView() {
        buxianTextView = (TextView) findViewById(R.id.buxian);
        domainTextView = (TextView) findViewById(R.id.domain);
        hotBrandGridView = (MyGridView) findViewById(R.id.hotView);
        mCategoryData = GPJApplication.getInstance().getCategoryData();
        hotBrandList = mCategoryData.mHotBrandList;
        hotBrandAdapter = new NewHotBrandAdapter(this, hotBrandList);
        hotBrandGridView.setAdapter(hotBrandAdapter);
        hotBrandGridView.setOnItemClickListener(this);
        registerTextView = (TextView) findViewById(R.id.register);
        mainView = findViewById(R.id.main_view);
        cityT = (TextView) findViewById(R.id.city);
        closeLl = (LinearLayout) findViewById(R.id.view_close);
        resetT = (TextView) findViewById(R.id.tv_reset);
        completeBtn = (TextView) findViewById(R.id.complete_but);
        start_priceT = (EditText) findViewById(R.id.start_price);
        end_priceT = (EditText) findViewById(R.id.end_price);
        registerTextView.setOnClickListener(this);
        cityT.setOnClickListener(this);
        closeLl.setOnClickListener(this);
        resetT.setOnClickListener(this);
        mainView.setOnClickListener(this);
        domainTextView.setOnClickListener(this);
        buxianTextView.setOnClickListener(this);
        //初始化GridView
        gV_brand = (MyGridView) findViewById(R.id.brand);
        gV_price = (MyGridView) findViewById(R.id.price);
        gv_color = (MyGridView) findViewById(R.id.carcolor);
        gV_carAge = (MyGridView) findViewById(R.id.carage);
        gV_carModel = (MyGridView) findViewById(R.id.carmodel);
        gV_carSource = (MyGridView) findViewById(R.id.carsource);
        gV_carProperty = (MyGridView) findViewById(R.id.carproperty);
        gV_displacement = (MyGridView) findViewById(R.id.displacement);
        gV_speedChange = (MyGridView) findViewById(R.id.speedchange);

        //初始化adapter
        adapter_color = new CarlistSelectFilterAdapter(this);
        adapter_brand = new CarlistSelectFilterAdapter(this);
        adapter_price = new CarlistSelectFilterAdapter(this);
        adapter_carAge = new CarlistSelectFilterAdapter(this);
        adapter_carModel = new CarlistSelectFilterAdapter(this);
        adapter_carSource = new CarlistSelectFilterAdapter(this);
        adapter_carProperty = new CarlistSelectFilterAdapter(this);
        adapter_displacement = new CarlistSelectFilterAdapter(this);
        adapter_speedChange = new CarlistSelectFilterAdapter(this);

        //添加adapter
        gv_color.setAdapter(adapter_color);
        gV_brand.setAdapter(adapter_brand);
        gV_price.setAdapter(adapter_price);
        gV_carAge.setAdapter(adapter_carAge);
        gV_carModel.setAdapter(adapter_carModel);
        gV_carSource.setAdapter(adapter_carSource);
        gV_carProperty.setAdapter(adapter_carProperty);
        gV_displacement.setAdapter(adapter_displacement);
        gV_speedChange.setAdapter(adapter_speedChange);

        //设置监听
        gv_color.setOnItemClickListener(this);
        gV_brand.setOnItemClickListener(this);
        gV_price.setOnItemClickListener(this);
        gV_carAge.setOnItemClickListener(this);
        gV_carModel.setOnItemClickListener(this);
        gV_carSource.setOnItemClickListener(this);
        gV_carProperty.setOnItemClickListener(this);
        gV_displacement.setOnItemClickListener(this);
        gV_speedChange.setOnItemClickListener(this);
        getSaveData();

        start_priceT.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String start = start_priceT.getText().toString();
                String end = end_priceT.getText().toString();
                if ((!TextUtils.isEmpty(start)) && (!TextUtils.isEmpty(end))) {
                    str_prices = start + "-" + end;
                    show_pricename = str_prices + "万";
                    resetRadio(list_prices);
                    adapter_price.setData(list_prices);
//                    Toast.makeText(CarListFilterActivity.this,str_prices,Toast.LENGTH_SHORT).show();
                    upData();
                }
            }
        });

        end_priceT.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String start = start_priceT.getText().toString();
                String end = end_priceT.getText().toString();
                if ((!TextUtils.isEmpty(start)) && (!TextUtils.isEmpty(end))) {
                    str_prices = start + "-" + end;
                    show_pricename = str_prices + "万";
                    resetRadio(list_prices);
                    adapter_price.setData(list_prices);
                    upData();
                }
            }
        });

    }

    //获取筛选条件
    private void getSaveData() {
        str_color = data.getColor();
        str_city = data.getCity();
        str_province = data.getProvince();
        mBrandSlug = data.getBrandSlug();
        mModelSlug = data.getModelSlug();
        mModelDetailSlug = data.getModel_detailSlug();
        mBrandName = data.getBrandName();
        mModelName = data.getModelName();
        mModelDetailName = data.getModel_detailName();
        str_prices = data.getPrice();
        str_carAge = data.getYear();
        str_carModel = data.getVehicle_model();
        str_carProperty = data.getCar_type();
        str_carSource = data.getCar_attribute();
        str_displacement = data.getCar_volume();
        str_speedChange = data.getControl();
        isCut = data.getIsCut();
        is_certify = data.getIs_certify();
        showcolor_name = data.getShow_color();
        showage_name = data.getShow_age();
        showmoder_name = data.getShow_vehicle_model();
        showcarProperty_name = data.getShow_car_type();
        show_carsourcename = data.getShow_source();
        show_speedchangename = data.getShow_speedchange();
        show_displacementname = data.getShow_displacement();
        show_pricename = data.getShow_price();

        str_domain = data.getCar_domain();
        show_domain = data.getShow_domain();
        str_mile = data.getMile();

        initGridView();
    }


    //重置数据
    private void resetData() {
        data.clear();
        getSaveData();
    }


    private void initGridView() {
        if (!TextUtils.isEmpty(str_province) && !TextUtils.isEmpty(str_city)) {
            cityT.setText(str_province + " " + str_city);
        } else if (TextUtils.isEmpty(str_province) && !TextUtils.isEmpty(str_city)) {
            cityT.setText(str_city);
        } else if (!TextUtils.isEmpty(str_province) && TextUtils.isEmpty(str_city)) {
            cityT.setText(str_province);
        } else {
            if (data.isCounty()) {
                cityT.setText("全国");
            } else {
                str_city = MainActivity.main.currentCity;
                cityT.setText(str_city);
            }
        }

        list_brands = new ArrayList<SelectBean>();
        String str_brands = mModelName + mModelDetailName;
        if (TextUtils.isEmpty(str_brands)) {
            str_brands = mBrandName;
        }
        for (int i = 0; i < brands.length; i++) {
            SelectBean bean = new SelectBean(brands[i], brands[i], false);
            if (TextUtils.isEmpty(str_brands)) {
                if (i == brands.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (i == 0) {
                    bean.setShow_name(str_brands);
                    bean.setCheack(true);
                }
            }
            list_brands.add(bean);
        }

        list_prices = new ArrayList<SelectBean>();
        if (!TextUtils.isEmpty(str_prices)) {
            List<String> list_prices = Arrays.asList(need_prices);
            if (!list_prices.contains(str_prices)) {
                setPrice(str_prices);
            }
        }
        for (int i = 0; i < show_prices.length; i++) {
            SelectBean bean = new SelectBean(show_prices[i], need_prices[i], false);
            if (TextUtils.isEmpty(str_prices)) {
                if (i == show_prices.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (str_prices.equals(need_prices[i])) {
                    bean.setCheack(true);
                }
            }
            list_prices.add(bean);
        }

        list_carAge = new ArrayList<SelectBean>();
        List<String> list_ages = Arrays.asList(str_carAge.split(","));
        for (int i = 0; i < show_carAge.length; i++) {
            SelectBean bean = new SelectBean(show_carAge[i], need_carAge[i], false);
            if (TextUtils.isEmpty(str_carAge)) {
                if (i == show_carAge.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_ages.contains(need_carAge[i])) {
                    bean.setCheack(true);
                }
            }
            list_carAge.add(bean);
        }

        list_carcolor = new ArrayList<SelectBean>();
        List<String> list_colors = Arrays.asList(str_color.split(","));
        for (int i = 0; i < show_color.length; i++) {
            SelectBean bean = new SelectBean(show_color[i], need_color[i], false);
            if (TextUtils.isEmpty(str_color)) {
                if (i == show_color.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_colors.contains(need_color[i])) {
                    bean.setCheack(true);
                }
            }
            list_carcolor.add(bean);
        }

        list_carModel = new ArrayList<SelectBean>();
        List<String> list_carmodels = Arrays.asList(str_carModel.split(","));
        for (int i = 0; i < show_carModel.length; i++) {
            SelectBean bean = new SelectBean(show_carModel[i], need_carModel[i], false);
            if (TextUtils.isEmpty(str_carModel)) {
                if (i == show_carModel.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_carmodels.contains(need_carModel[i])) {
                    bean.setCheack(true);
                }
            }
            list_carModel.add(bean);
        }

        list_carSource = new ArrayList<SelectBean>();
        List<String> list_carsources = Arrays.asList(str_carSource.split(","));
        for (int i = 0; i < show_carSource.length; i++) {
            SelectBean bean = new SelectBean(show_carSource[i], need_carSource[i], false);
            if (TextUtils.isEmpty(str_carSource)) {
                if (i == show_carSource.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_carsources.contains(need_carSource[i])) {
                    bean.setCheack(true);
                }
            }
            list_carSource.add(bean);
        }

        list_carProperty = new ArrayList<SelectBean>();
        List<String> list_carprops = Arrays.asList(str_carProperty.split(","));
        for (int i = 0; i < show_carProperty.length; i++) {
            SelectBean bean = new SelectBean(show_carProperty[i], need_carProperty[i], false);
            if (TextUtils.isEmpty(str_carProperty)) {
                if (i == show_carProperty.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_carprops.contains(need_carProperty[i])) {
                    bean.setCheack(true);
                }
            }
            list_carProperty.add(bean);
        }

        list_displacement = new ArrayList<SelectBean>();
        List<String> list_displacements = Arrays.asList(str_displacement.split(","));
        for (int i = 0; i < show_displacement.length; i++) {
            SelectBean bean = new SelectBean(show_displacement[i], need_displacement[i], false);
            if (TextUtils.isEmpty(str_displacement)) {
                if (i == show_displacement.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_displacements.contains(need_displacement[i])) {
                    bean.setCheack(true);
                }
            }
            list_displacement.add(bean);
        }

        list_speedChange = new ArrayList<SelectBean>();
        List<String> list_speeds = Arrays.asList(str_speedChange.split(","));
        for (int i = 0; i < show_speedChange.length; i++) {
            SelectBean bean = new SelectBean(show_speedChange[i], need_speedChange[i], false);
            if (TextUtils.isEmpty(str_speedChange)) {
                if (i == show_speedChange.length - 1) {
                    bean.setCheack(true);
                }
            } else {
                if (list_speeds.contains(need_speedChange[i])) {
                    bean.setCheack(true);
                }
            }
            list_speedChange.add(bean);
        }
        adapter_color.setData(list_carcolor);
        adapter_brand.setData(list_brands);
        adapter_price.setData(list_prices);
        adapter_carAge.setData(list_carAge);
        adapter_carModel.setData(list_carModel);
        adapter_carSource.setData(list_carSource);
        adapter_carProperty.setData(list_carProperty);
        adapter_displacement.setData(list_displacement);
        adapter_speedChange.setData(list_speedChange);

        if (!TextUtils.isEmpty(show_domain)) {
            if (show_domain.endsWith(",")) {
                domainTextView.setText(show_domain.substring(0, show_domain.length() - 1));
            } else {
                domainTextView.setText(show_domain);
            }
            buxianTextView.setBackgroundResource(R.drawable.discount_filter_normal);
            buxianTextView.setTextColor(getResources().getColor(R.color.text_details_color));
            domainTextView.setBackgroundResource(R.drawable.button_big_bg_normal);
            domainTextView.setTextColor(getResources().getColor(R.color.white));
        }
        //第一次加载时
        upData();
    }

    //重置单选 (设置为false)
    private void resetRadio(List<SelectBean> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setCheack(false);
        }
    }

    //重置多选
    private String resetChecked(List<SelectBean> list, int position) {
        SelectBean sb = list.get(position);
        boolean ischeck = sb.isCheack();
        if (position != list.size() - 1) {       //当前选中item不为最后一个
            sb.setCheack(!ischeck);
            list.get(list.size() - 1).setCheack(false);     //最后一个item为false
        } else {      //选择最后一个item
            //最后item为true其他为false
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setCheack(false);
            }
            sb.setCheack(true);
        }

        List<String> checkedName = new ArrayList<String>();       //将为true的字段保存在当前集合
        List<String> checkedShowName = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isCheack()) {
                if (i == list.size() - 1) {      //如果最后一个为true  存为""
                    checkedName.add("");
                } else {
                    checkedName.add(list.get(i).getNeed_name());
                    checkedShowName.add(list.get(i).getShow_name());
                }

            }
        }

        if (checkedName.isEmpty()) {          //如果全部为false 将最后一个设置为true
            checkedName.add("");
            list.get(list.size() - 1).setCheack(true);
            checkedShowName.clear();
        }
        String str_name = setcomposing(checkedName);
        String show_name = setcomposing(checkedShowName);
//        Toast.makeText(this,str_name,Toast.LENGTH_SHORT).show();
        return str_name + "&" + show_name;

    }

    //拼接字符串
    private String setcomposing(List<String> checkedName) {
        String names = "";
        for (int i = 0; i < checkedName.size(); i++) {
            if (i == checkedName.size() - 1) {
                names += checkedName.get(i);
            } else {
                names += checkedName.get(i) + ",";
            }
        }
        return names;
    }

    private void setPrice(String price) {
        String[] prices = price.split("-");
        if (prices.length == 2) {
            start_priceT.setText(prices[0]);
            end_priceT.setText(prices[1]);
        } else {
            start_priceT.setText("");
            end_priceT.setText("");
        }

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String datas[];
        switch (parent.getId()) {
            //品牌    (单选)
            case R.id.brand:
                resetRadio(list_brands);
                if (0 == position) {  //选择品牌
                    clickManualBrand();
                } else {
                    this.data.setIsCounty(false);
                    str_city = MainActivity.main.currentCity;
                    this.data.setIsCanClick(true);
                    list_brands.get(position).setCheack(true);
                    list_brands.get(0).setShow_name(brands[0]);
                    adapter_brand.setData(list_brands);
                    data.clearModelData();
                    str_carModel = "";
                    str_carProperty = "";
                    str_displacement = "";
                    str_speedChange = "";
                    mBrandSlug = "";
                    mBrandName = "";
                    mModelSlug = "";
                    mModelName = "";
                    mModelDetailName = "";
                    mModelDetailSlug = "";
                    mModelThumbnail = "";
                    initGridView();
                }
                break;
            case R.id.hotView:
                HashMap<String, String> map = (HashMap<String, String>) hotBrandAdapter.getItem(position);
                Intent intent = new Intent();
                intent.setClass(this, CategoryActivity.class);
                intent.putExtra(Const.BRAND_NAME_KEY, map.get("name"));
                intent.putExtra(Const.BRAND_SLUG_KEY, map.get("slug"));
                intent.putExtra(Const.MODEL_NAME_KEY, "");
                intent.putExtra(Const.MODEL_SLUG_KEY, "");
                intent.putExtra(Const.MODEL_DETAIL_NAME_KEY, "");
                intent.putExtra(Const.MODEL_DETAIL_SLUG_KEY, "");
                intent.putExtra("isFromFilter", true);
                intent.putExtra("needModelDetailFragment", false);
                startActivityForResult(intent, REQUEST_BRAND);
                break;
            //价格    (单选)
            case R.id.price:
                resetRadio(list_prices);
                list_prices.get(position).setCheack(true);
                adapter_price.setData(list_prices);
                str_prices = list_prices.get(position).getNeed_name();
                show_pricename = list_prices.get(position).getShow_name();
//                setPrice(str_prices);
                start_priceT.setText("");
                end_priceT.setText("");
//                Toast.makeText(CarListFilterActivity.this,str_prices,Toast.LENGTH_SHORT).show();
                upData();
                break;
            //车龄    (多选)
            case R.id.carage:
                datas = resetChecked(list_carAge, position).split("&");
                if (datas.length >= 1)
                    str_carAge = datas[0];
                else str_carAge = "";
                if (datas.length >= 2)
                    showage_name = datas[1];
                else showage_name = "";
                adapter_carAge.setData(list_carAge);
                upData();
                break;
            case R.id.carcolor:
                datas = resetChecked(list_carcolor, position).split("&");
                if (datas.length >= 1)
                    str_color = datas[0];
                else str_color = "";
                if (datas.length >= 2)
                    showcolor_name = datas[1];
                else showcolor_name = "";
                adapter_color.setData(list_carcolor);
                upData();
                break;
            //车型    (多选)
            case R.id.carmodel:
                if (!data.isCanClick()) {
                    showDiaglogFilter(0, position);
                    return;
                }
                datas = resetChecked(list_carModel, position).split("&");
                if (datas.length >= 1)
                    str_carModel = datas[0];
                else str_carModel = "";
                if (datas.length >= 2)
                    showmoder_name = datas[1];
                else showmoder_name = "";
                adapter_carModel.setData(list_carModel);
                upData();
                break;
            //车源类型  (多选)
            case R.id.carsource:
                datas = resetChecked(list_carSource, position).split("&");
                if (datas.length >= 1)
                    str_carSource = datas[0];
                else str_carSource = "";
                if (datas.length >= 2)
                    show_carsourcename = datas[1];
                else show_carsourcename = "";
                adapter_carSource.setData(list_carSource);
                upData();
                break;
            //车辆属性  (多选)
            case R.id.carproperty:
                if (!data.isCanClick()) {
                    showDiaglogFilter(1, position);
                    return;
                }
                datas = resetChecked(list_carProperty, position).split("&");
                if (datas.length >= 1)
                    str_carProperty = datas[0];
                else str_carProperty = "";
                if (datas.length >= 2)
                    showcarProperty_name = datas[1];
                else showcarProperty_name = "";
                adapter_carProperty.setData(list_carProperty);
                upData();
                break;
            //排量    (单选)
            case R.id.displacement:
                if (!data.isCanClick()) {
                    showDiaglogFilter(2, position);
                    return;
                }
                datas = resetChecked(list_displacement, position).split("&");
                if (datas.length >= 1)
                    str_displacement = datas[0];
                else str_displacement = "";
                if (datas.length >= 2)
                    show_displacementname = datas[1];
                else show_displacementname = "";
                adapter_displacement.setData(list_displacement);
                upData();
                break;
            //变速箱 (多选)
            case R.id.speedchange:
                if (!data.isCanClick()) {
                    showDiaglogFilter(3, position);
                    return;
                }
                datas = resetChecked(list_speedChange, position).split("&");
                if (datas.length >= 1)
                    str_speedChange = datas[0];
                else str_speedChange = "";
                if (datas.length >= 2)
                    show_speedchangename = datas[1];
                else show_speedchangename = "";
                adapter_speedChange.setData(list_speedChange);
                upData();


//                str_speedChange = resetChecked(list_speedChange, position);
//                adapter_speedChange.setData(list_speedChange);
//                upData();
                break;
        }
    }


    private void showDiaglogFilter(final int type, final int position) {
        AlertDialog.Builder ad = new AlertDialog.Builder(this);
        ad.setTitle("提示");
        ad.setMessage("该配置是该车型的出厂标准配置，修改配置后可能无法为您找到您需要的车辆。");
        ad.setPositiveButton("取消修改", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        ad.setNegativeButton("确认条件", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                data.setIsCanClick(true);
                String datas[];
                if (type == 0) {
                    datas = resetChecked(list_carModel, position).split("&");
                    if (datas.length >= 1)
                        str_carModel = datas[0];
                    else str_carModel = "";
                    if (datas.length >= 2)
                        showmoder_name = datas[1];
                    else showmoder_name = "";
                    adapter_carModel.setData(list_carModel);
                    upData();
                } else if (type == 1) {
                    datas = resetChecked(list_carProperty, position).split("&");
                    if (datas.length >= 1)
                        str_carProperty = datas[0];
                    else str_carProperty = "";
                    if (datas.length >= 2)
                        showcarProperty_name = datas[1];
                    else showcarProperty_name = "";
                    adapter_carProperty.setData(list_carProperty);
                    upData();
                } else if (type == 2) {
                    datas = resetChecked(list_displacement, position).split("&");
                    if (datas.length >= 1)
                        str_displacement = datas[0];
                    else str_displacement = "";
                    if (datas.length >= 2)
                        show_displacementname = datas[1];
                    else show_displacementname = "";
                    adapter_displacement.setData(list_displacement);
                    upData();
                } else if (type == 3) {
                    datas = resetChecked(list_speedChange, position).split("&");
                    if (datas.length >= 1)
                        str_speedChange = datas[0];
                    else str_speedChange = "";
                    if (datas.length >= 2)
                        show_speedchangename = datas[1];
                    else show_speedchangename = "";
                    adapter_speedChange.setData(list_speedChange);
                    upData();
                }
            }
        });
        ad.create().show();
    }


    @Override
    public void onDataJsonError(String errorMessage) {
//        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDataJsonUpdate(JSONObject json) {
        try {
            setSearchResult(json.getString("count"));
        } catch (JSONException e) {
            Toast.makeText(this, "未找到相应数据", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    int num = 0;

    public void setSearchResult(String num1) {
        num = Integer.parseInt(num1);
        completeBtn.setText("立刻查看\n目前共找到 " + num + " 辆车源");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.city:     //城市选择
                clickLocation();
                break;
            case R.id.view_close:   //关闭当前页
                finish();
                break;
            case R.id.tv_reset:     //重置选项
                start_priceT.setText("");
                end_priceT.setText("");
                resetData();
                initGridView();
                break;
            case R.id.main_view:     //完成提交
                saveFilterData();
                setResult(Activity.RESULT_OK);
                finish();
                break;
            case R.id.register:
                if (num > 100) {
                    showDialog();
                } else {
                    register();
                }
                break;
            case R.id.domain:
                if (mDomains == null) {
                    mDomains = new ArrayList<>();
                }
                Intent intent = new Intent();
                intent.putExtra("domainString", show_domain);
                intent.setClass(this, DomainActivity.class);
                startActivityForResult(intent, REQUEST_DOMAIN);
                break;
            case R.id.buxian:
                buxianTextView.setBackgroundResource(R.drawable.button_big_bg_normal);
                buxianTextView.setTextColor(getResources().getColor(R.color.white));
                if (mDomains != null) {
                    mDomains.clear();
                }
                show_domain = "";
                str_domain = "";
                domainTextView.setText("渠道选择");
                domainTextView.setBackgroundResource(R.drawable.discount_filter_normal);
                domainTextView.setTextColor(getResources().getColor(R.color.text_details_color));
                upData();
                break;
//            case R.id.city_select:
//                Intent intent = new Intent();
//                intent.setClass(this, CitySelectAvtivity.class);
//                startActivityForResult(intent , REQUEST_MORE_CITY);
//                break;
        }
    }


    private void register() {
        StepMonitor.getInstance().addMonitor(new Monitor("click", "buy_market_filter_subscribe", System.currentTimeMillis(), roll_pages));
        if (registerNetDataJson == null) {
            registerNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    loadingDialog.dismiss();
                    Toast.makeText(CarListFilterActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    loadingDialog.dismiss();
                    Toast.makeText(CarListFilterActivity.this, "订阅成功", Toast.LENGTH_SHORT).show();
                }
            });
        }

        registerNetDataJson.addParam("city", str_city);
        registerNetDataJson.addParam("brand", mBrandSlug);
        registerNetDataJson.addParam("model", mModelSlug);
        registerNetDataJson.addParam("vehicle_model", str_carModel);
        registerNetDataJson.addParam("price", str_prices);
        registerNetDataJson.addParam("year", str_carAge);
        registerNetDataJson.addParam("car_type", str_carProperty);
        registerNetDataJson.addParam("colors", str_color);
        registerNetDataJson.addParam("control", str_speedChange);
        registerNetDataJson.addParam("car_volume", str_displacement);
        registerNetDataJson.addParam("car_attribute", str_carSource);
        registerNetDataJson.addParam("province", str_province);
        registerNetDataJson.setUrl(API.find_cars);
        registerNetDataJson.request("post");
        loadingDialog.show();

    }


    private void showDialog() {
        AlertDialog.Builder ad = new AlertDialog.Builder(this);
        ad.setTitle("提示");
        ad.setMessage("您的条件过于宽泛，为给您提供精准的车源，建议您细化选车条件。");
        ad.setPositiveButton("继续细化", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        ad.setNegativeButton("确认条件", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                register();
            }
        });
        ad.create().show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent agr1) {
        super.onActivityResult(requestCode, resultCode, agr1);
        if (resultCode == Activity.RESULT_OK) {
            //品牌
            if (requestCode == REQUEST_BRAND) {
                bundle = agr1.getExtras();
                data.cleanBrand();
                mBrandSlug = bundle.getString("brandSlug", "");
                mBrandName = bundle.getString("brandName", "");
                mModelSlug = bundle.getString("modelSlug", "");
                mModelName = bundle.getString("modelName", "");
                mModelDetailName = bundle.getString("modelDetailName", "");
                mModelDetailSlug = bundle.getString("modelDetailSlug", "");
                mModelThumbnail = bundle.getString("modelThumbnail", "");
                maxprice = bundle.getString("maxprice", "");

                String showText = mModelName + mModelDetailName;
                if ("".equals(showText))
                    showText = mBrandName;

                if ("".equals(mModelSlug) || "".equals(mBrandSlug)) {
                    data.setIsCanClick(true);
                    data.clearModelData();
                    str_carModel = "";
                    str_carProperty = "";
                    str_displacement = "";
                    str_speedChange = "";
                    this.data.setIsCounty(false);
                    str_city = MainActivity.main.currentCity;
                    initGridView();
                } else {
                    getModelDetailData(mBrandSlug, mModelSlug);
                    list_brands.get(0).setCheack(true);
                    list_brands.get(0).setShow_name(showText);
                    list_brands.get(0).setNeed_name(showText);
                    adapter_brand.setData(list_brands);
                }
                //城市
            } else if (requestCode == REQUEST_CITY_FRAGMENT) {
                Bundle b = agr1.getExtras();
                str_city = b.getString("citylist", "");
                str_province = b.getString("province_list", "");
                if (!TextUtils.isEmpty(str_province) && !TextUtils.isEmpty(str_city)) {
                    cityT.setText(str_province + " " + str_city);
                    data.setIsCounty(false);
                } else if (TextUtils.isEmpty(str_province) && !TextUtils.isEmpty(str_city)) {
                    cityT.setText(str_city);
                    data.setIsCounty(false);
                } else if (!TextUtils.isEmpty(str_province) && TextUtils.isEmpty(str_city)) {
                    cityT.setText(str_province);
                    data.setIsCounty(false);
                } else {
                    data.setIsCounty(true);
                    cityT.setText("全国");
                }
                upData();
            } else if (requestCode == REQUEST_DOMAIN) {
                Bundle b = agr1.getExtras();
                mDomains = b.getParcelableArrayList("Domain");
                String title = getDomainString();
                if (TextUtils.isEmpty(title)) {
                    buxianTextView.setBackgroundResource(R.drawable.button_big_bg_normal);
                    buxianTextView.setTextColor(getResources().getColor(R.color.white));
                    domainTextView.setBackgroundResource(R.drawable.discount_filter_normal);
                    domainTextView.setTextColor(getResources().getColor(R.color.text_details_color));
                    if (mDomains != null) {
                        mDomains.clear();
                    }
                    show_domain = "";
                    str_domain = "";
                    domainTextView.setText("渠道选择");
                }
                buxianTextView.setBackgroundResource(R.drawable.discount_filter_normal);
                buxianTextView.setTextColor(getResources().getColor(R.color.text_details_color));
                domainTextView.setBackgroundResource(R.drawable.button_big_bg_normal);
                domainTextView.setTextColor(getResources().getColor(R.color.white));
                domainTextView.setText(title);
                upData();
            }
        }
    }

    private String getDomainString() {

        if (mDomains == null || mDomains.size() == 0) {
            show_domain = "";
            str_domain = "";
            return "";
        }
        int size = mDomains.size();
        StringBuilder sb = new StringBuilder();
        StringBuilder value = new StringBuilder();
        for (int i = 0; i < size; i++) {
            if (mDomains.get(i).isCheck()) {
                if (i == size - 1) {
                    sb.append(mDomains.get(i).getName());
                    value.append(mDomains.get(i).getValue());
                } else {
                    sb.append(mDomains.get(i).getName()).append(",");
                    value.append(mDomains.get(i).getValue()).append(",");
                }
            }
        }
        show_domain = sb.toString();
        str_domain = value.toString();
        return show_domain;
    }


    //选择品牌
    private void clickManualBrand() {
        Intent intent = new Intent();
        intent.setClass(this, CategoryActivity.class);
        intent.putExtra(Const.BRAND_NAME_KEY, mBrandName);
        intent.putExtra(Const.BRAND_SLUG_KEY, mBrandSlug);
        intent.putExtra(Const.MODEL_NAME_KEY, mModelName);
        intent.putExtra(Const.MODEL_SLUG_KEY, mModelSlug);

        intent.putExtra("needModelDetailFragment", false);
        intent.putExtra("isFromFilter", true);
        startActivityForResult(intent, REQUEST_BRAND);
    }

    //选择城市
    private void clickLocation() {
        Intent intent = new Intent();
        intent.setClass(this, CitySelectAvtivity.class);
        if (!TextUtils.isEmpty(mModelSlug)) {
            intent.putExtra("show_county", true);
        }
        startActivityForResult(intent, REQUEST_CITY_FRAGMENT);
    }


    //判断价格是否合法
    private boolean priceInvaid(String price) {
        String[] prices = price.split("-");
        if (prices.length == 2) {
            int front = Integer.parseInt(prices[0]);
            int back = Integer.parseInt(prices[1]);
            if (back < front) {
                //价格填写错误
                return false;
            }
        }

        return true;
    }


    private void upData() {
//        if (!TextUtils.isEmpty(str_prices)) {
//           if(!priceInvaid(str_prices)){
//               return;
//           }
//        }
        netWork.clearMap();
        if (!TextUtils.isEmpty(str_city))
            netWork.addParam("city", str_city);
        if (!TextUtils.isEmpty(str_province))
            netWork.addParam("province", str_province);
        if (!TextUtils.isEmpty(mBrandSlug))
            netWork.addParam("brand", mBrandSlug);
        if (!TextUtils.isEmpty(mModelSlug))
            netWork.addParam("model", mModelSlug);
        if (!TextUtils.isEmpty(mModelDetailSlug))
            netWork.addParam("model_detail", mModelDetailSlug);
        if (!TextUtils.isEmpty(str_prices))
            netWork.addParam("price", str_prices);
        if (!TextUtils.isEmpty(str_carAge))
            netWork.addParam("year", str_carAge);
        if (!TextUtils.isEmpty(str_color))
            netWork.addParam("colors", str_color);
        if (!TextUtils.isEmpty(str_carModel))
            netWork.addParam("vehicle_model", str_carModel);
        if (!TextUtils.isEmpty(str_carProperty))
            netWork.addParam("car_type", str_carProperty);
        if (!TextUtils.isEmpty(str_carSource))
            netWork.addParam("car_attribute", str_carSource);
        if (!TextUtils.isEmpty(str_displacement))
            netWork.addParam("car_volume", str_displacement);
        if (!TextUtils.isEmpty(str_speedChange))
            netWork.addParam("control", str_speedChange);
        if (!TextUtils.isEmpty(str_domain))
            netWork.addParam("domain", str_domain);
        if (!TextUtils.isEmpty(str_mile))
            netWork.addParam("mile", str_mile);
        netWork.addParam("is_cut_price", isCut);
        netWork.addParam("is_certify", is_certify);
        netWork.request("get");
    }

    //保存筛选条件
    private void saveFilterData() {
        data.setCity(str_city);
        data.setBrandSlug(mBrandSlug);
        data.setModelSlug(mModelSlug);
        data.setModel_detailSlug(mModelDetailSlug);
        data.setBrandName(mBrandName);
        data.setModelName(mModelName);
        data.setModel_detailName(mModelDetailName);
        data.setPrice(str_prices);
        data.setYear(str_carAge);
        data.setVehicle_model(str_carModel);
        data.setCar_type(str_carProperty);
        data.setCar_attribute(str_carSource);
        data.setCar_volume(str_displacement);
        data.setColor(str_color);
        data.setControl(str_speedChange);
        data.setProvince(str_province);

        data.setShow_price(show_pricename);
        data.setShow_age(showage_name);
        data.setShow_vehicle_model(showmoder_name);
        data.setShow_car_type(showcarProperty_name);
        data.setShow_source(show_carsourcename);
        data.setShow_displacement(show_displacementname);
        data.setShow_speedchange(show_speedchangename);
        data.setShow_color(showcolor_name);

        data.setShow_domain(show_domain);
        data.setCar_domain(str_domain);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (netWork != null) {
            netWork.cancelTask();
        }
        if (modelDetailnetWork != null) {
            modelDetailnetWork.cancelTask();
        }

        if (registerNetDataJson != null) {
            registerNetDataJson.cancelTask();
        }
    }


    private void getModelDetailData(String brand, String model) {
        if (modelDetailnetWork == null) {
            modelDetailnetWork = new NetDataJson(new NetDataJson.OnStringListener() {
                @Override
                public void onDataJsonError(String errorMessage) {
                    data.setIsCanClick(true);
                }

                @Override
                public void onDataJsonUpdate(String json) {
                    try {
                        Gson gson = new Gson();
                        ModelDetialBean modelDetialBean = gson.fromJson(json, ModelDetialBean.class);
                        if ("success".equals(modelDetialBean.getStatus())) {
                            getFilterDataFromNet(modelDetialBean);
                        }
                    } catch (Exception e) {
                        data.setIsCanClick(true);
                    }
                }
            }, 1);
        }
        modelDetailnetWork.setUrl(API.modelDetail);
        modelDetailnetWork.addParam("brand", brand);
        modelDetailnetWork.addParam("model", model);
        modelDetailnetWork.request("get");
    }

    private void getFilterDataFromNet(ModelDetialBean modelDetialBean) {
        //车型
        TreeSet<String> vehicleModelSet = new TreeSet<>();
        //产地
        TreeSet<String> carTypeSet = new TreeSet<>();
        //变速箱
        TreeSet<String> controlSet = new TreeSet<>();
        //排量
        TreeSet<String> volumeSet = new TreeSet<>();
        double maxprice = 0;
        for (ModelDetialBean.DetailModelEntity detailModelEntities : modelDetialBean.getDetail_model()) {
            double max = Double.parseDouble(detailModelEntities.getPrice_bn());
            if (max >= maxprice) {
                maxprice = max;
            }
            vehicleModelSet.add(detailModelEntities.getVehicle_model());
            carTypeSet.add(detailModelEntities.getCar_type());
            controlSet.add(detailModelEntities.getControl());
            volumeSet.add(detailModelEntities.getVolume());
        }
        data.setMax_price((int) maxprice + "");
        volumeSet.comparator();
        data.clearModelData();
        str_carModel = "";
        str_carProperty = "";
        str_displacement = "";
        str_speedChange = "";
        showmoder_name = "";
        show_speedchangename = "";
        showcarProperty_name = "";
        show_displacementname = "";

        int size;
        size = need_carModel.length;
        //遍历车型
        for (String str : vehicleModelSet) {
            for (int i = 0; i < size; i++) {
                if (str.equals(need_carModel[i])) {
                    showmoder_name = showmoder_name + show_carModel[i] + ",";
                }
            }
            str_carModel = str_carModel + str + ",";
        }
        if (!TextUtils.isEmpty(str_carModel)) {
            str_carModel = str_carModel.substring(0, str_carModel.length() - 1);
        }
        if (!TextUtils.isEmpty(showmoder_name)) {
            showmoder_name = showmoder_name.substring(0, showmoder_name.length() - 1);
        }

        size = need_carProperty.length;
        //遍历产地
        for (String str : carTypeSet) {
            for (int i = 0; i < size; i++) {
                if (str.equals(need_carProperty[i])) {
                    showcarProperty_name = showcarProperty_name + show_carProperty[i] + ",";
                }
            }
            str_carProperty = str_carProperty + str + ",";
        }
        if (!TextUtils.isEmpty(str_carProperty)) {
            str_carProperty = str_carProperty.substring(0, str_carProperty.length() - 1);
        }
        if (!TextUtils.isEmpty(showcarProperty_name)) {
            showcarProperty_name = showcarProperty_name.substring(0, showcarProperty_name.length() - 1);
        }


        size = need_speedChange.length;
        //遍历变速箱
        for (String str : controlSet) {
            for (int i = 0; i < size; i++) {
                if (str.equals(need_speedChange[i])) {
                    show_speedchangename = show_speedchangename + show_speedChange[i] + ",";
                }
            }
            str_speedChange = str_speedChange + str + ",";
        }
        if (!TextUtils.isEmpty(str_speedChange)) {
            str_speedChange = str_speedChange.substring(0, str_speedChange.length() - 1);
        }
        if (!TextUtils.isEmpty(show_speedchangename)) {
            show_speedchangename = show_speedchangename.substring(0, show_speedchangename.length() - 1);
        }
        //遍历排量
        for (String str : volumeSet) {
            float volume = Float.parseFloat(str);
            if (volume <= 1.0f) {
                if (str_displacement.contains("0-1.0")) continue;
                str_displacement = str_displacement + "0-1.0" + ",";
                show_displacementname = show_displacementname + "1.0升以内" + ",";
            } else if (volume <= 1.6f && volume >= 1.1f) {
                if (str_displacement.contains("1.1-1.6")) continue;
                str_displacement = str_displacement + "1.1-1.6" + ",";
                show_displacementname = show_displacementname + "1.1-1.6升" + ",";
            } else if (volume <= 2.0f && volume >= 1.7f) {
                if (str_displacement.contains("1.7-2.0")) continue;
                str_displacement = str_displacement + "1.7-2.0" + ",";
                show_displacementname = show_displacementname + "1.7-2.0升" + ",";
            } else if (volume <= 2.5f && volume >= 2.1f) {
                if (str_displacement.contains("2.1-2.5")) continue;
                str_displacement = str_displacement + "2.1-2.5" + ",";
                show_displacementname = show_displacementname + "2.1-2.5升" + ",";
            } else if (volume <= 10.0f && volume >= 2.6f) {
                if (str_displacement.contains("2.6-10.0")) continue;
                str_displacement = str_displacement + "2.6-10.0" + ",";
                show_displacementname = show_displacementname + "2.5升以上" + ",";
            }
        }
        if (!TextUtils.isEmpty(str_displacement)) {
            str_displacement = str_displacement.substring(0, str_displacement.length() - 1);
        }
        if (!TextUtils.isEmpty(show_displacementname)) {
            show_displacementname = show_displacementname.substring(0, show_displacementname.length() - 1);
        }
        data.setIsCanClick(false);
        initGridView();
    }


}
